import router from "@/router";
import store from "@/store";
import axios from "axios";
import { ElLoading } from "element-plus";

const service = axios.create({
    baseURL: "http://localhost:8088/bookmall",
    timeout: 20000,
    withCredentials: false,
    headers: {
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "Access-Control-Allow-Origin": "*",
    },
});

let loading;

function startLoading() {
    loading = ElLoading.service({
        lock: true,
        text: "拼命加载中...",
    });
}

function endLoading() {
    loading.close();
}

service.interceptors.request.use(
    (config) => {
        startLoading();
        // store.commit("checkLogin");
        config.headers["token"] = localStorage.getItem("token") === null ? "" : localStorage.getItem("token");
        return config;
    },
    (error) => {
        console.log("Request Reject: ", error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    (response) => {
        setTimeout(() => {
            endLoading();
        }, 200);
        if (response.status === 200) {
            if (response.data.code === 401) {
                router.replace({ name: "login" });
                store.commit("logout");
                window.location.reload();
            }
            return response.data;
        } else {
            Promise.reject();
        }
    },
    (error) => {
        setTimeout(() => {
            endLoading();
        }, 200);
        console.log(error);
        return Promise.reject();
    }
);

export default service;
